#-*- coding: UTF-8 -*- 
import sys
sys.path.append('/home/xd233/.local/lib/python3.6/site-packages')
import cv2
import time
import socket
import nanocamera as nano
from utils import im2coordinate
import os
import numpy as np
import glob
import pickle

# 服务端ip地址
HOST = '192.168.1.110'
# 服务端端口号
PORT = 8081
ADDRESS = (HOST, PORT)
width=1280
height=720
camera_2 = nano.Camera(device_id=0, flip=0, width=width, height=height, fps=30)  #
camera_1= nano.Camera(device_id=1, flip=2, width=width, height=height, fps=60)  #

# 创建一个套接字
tcpClient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接远程ip
tcpClient.connect(ADDRESS)

with open('mtx.pickle',"rb") as f1:
    mtx = pickle.load(f1)
with open('dist.pickle',"rb") as f1:
    dist = pickle.load(f1)

h,  w = height,width 
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w,h), 1, (w,h))

# undistort
mapx, mapy = cv2.initUndistortRectifyMap(mtx, dist, None, newcameramtx, (w,h), 5)
#
while True:
    num=len(os.listdir("./shot"))
    # 计时
    start = time.perf_counter()
    # 读取图像
    cv_image = camera_2.read()
    
    dst = cv2.remap(cv_image, mapx, mapy, cv2.INTER_LINEAR)
    # crop the image
    x, y, w, h = roi
    cv_image = dst[y:y+h, x:x+w]

    if len(os.listdir("./shot/shot_flag"))==1:
        cv2.imwrite("./shot/"+str(num-1)+".png",cv_image)
        os.remove("/home/xd233/gd_code/shot/shot_flag/1")
        print(str(num-1)+".jpg is saved")
    #x_record=im2coordinate(cv_image)
   # cv2.circle(cv_image,(x_record,615),5,(213,0,0),-1)
    
    cv_image=cv2.resize(cv_image,(int(1280//1.5),int(720//1.5)))
    # 压缩图像
    img_encode = cv2.imencode('.jpg', cv_image, [cv2.IMWRITE_JPEG_QUALITY, 99])[1]
    # 转换为字节流
    bytedata = img_encode.tostring()
    # 标志数据，包括待发送的字节流长度等数据，用‘,’隔开
    flag_data = (str(len(bytedata))).encode() + ",".encode() + " ".encode()

    tcpClient.send(flag_data)
    # 接收服务端的应答
    data = tcpClient.recv(1024)
    if ("ok" == data.decode()):
        # 服务端已经收到标志数据，开始发送图像字节流数据
        tcpClient.send(bytedata)
    # 接收服务端的应答
    data = tcpClient.recv(1024)
    if ("ok" == data.decode()):
        # 计算发送完成的延时
       # print("延时：" + str(int((time.perf_counter() - start) * 1000)) + "ms")
       pass
